package com.wang.jmonkey.ca.handler.login.success;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.wang.jmonkey.common.constant.SecurityConstant;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 刷新access token
 * @Author HeJiawang
 * @Date 2021/5/14 14:30
 */
@Component
public class RefreshTokenBuildHandler implements TokenBuildHandlerAdapter {

    @Autowired
    private AuthorizationServerTokenServices authorizationServerTokenServices;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private TokenStore tokenStore;

    @Override
    public OAuth2AccessToken handler(HttpServletRequest request, Authentication authentication) {
        logoutExisting(authentication);

        TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP,
                SecurityConstant.clientsKey.Client_Id.getKey(),
                CollUtil.newHashSet(SecurityConstant.clientsKey.Scopes.getKey()),
                SecurityConstant.clientsKey.Grant_Type_Refresh_Token.getKey());


        return authorizationServerTokenServices.refreshAccessToken(
                        request.getAttribute(SecurityConstant.LoginParameter.refreshToken.getKey()).toString(),
                        tokenRequest
                );
    }

    @Override
    public boolean support(String oauthType) {
        return StrUtil.isNotEmpty(oauthType)
                && oauthType.equalsIgnoreCase(SecurityConstant.OAuthType.refresh_token.getKey());
    }

    /**
     * 退出已登录信息
     * @param authentication authentication
     */
    private void logoutExisting(Authentication authentication) {
        TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP,
                SecurityConstant.clientsKey.Client_Id.getKey(),
                CollUtil.newHashSet(SecurityConstant.clientsKey.Scopes.getKey()),
                SecurityConstant.clientsKey.Grant_Type_Password.getKey());

        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(SecurityConstant.clientsKey.Client_Id.getKey());
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oauth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);

        // 清除已登录信息
        OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(oauth2Authentication);
        if (!ObjectUtils.isEmpty(existingAccessToken)) {
            tokenStore.removeAccessToken(existingAccessToken);
        }
    }
}
